package cn.zl.ymcc.mq;

import cn.zl.ymcc.service.CourseOrderService;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
public class OrderTransactionListener implements TransactionListener {

    @Autowired
    @Lazy
    private CourseOrderService orderService;

    /**
     * 执行本地事务
     */
    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {

        try {
            String messageBody = new String(msg.getBody(), StandardCharsets.UTF_8);
            System.out.println("执行本地事务，TransactionId: " +  ", 消息: " + messageBody);
            //messagebody为订单ID arg为课程ID
            // 执行订单支付业务逻辑
            boolean success = orderService.processOrderPayment(messageBody, arg);
            
            if (success) {
                System.out.println("本地事务执行成功，提交消息，TransactionId: ");
                return LocalTransactionState.COMMIT_MESSAGE;
            } else {
                System.out.println("本地事务执行失败，回滚消息，TransactionId: ");
                return LocalTransactionState.ROLLBACK_MESSAGE;
            }
        } catch (Exception e) {
            System.err.println("本地事务执行异常，TransactionId: "  + ", 错误: " + e.getMessage());
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
    }

    /**
     * 本地事务回查
     */
    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt msg) {
        String transactionId = msg.getTransactionId();
        try {
            String messageBody = new String(msg.getBody(), StandardCharsets.UTF_8);
            System.out.println("执行本地事务回查，TransactionId: " + transactionId + ", 消息: " + messageBody);
            
            // 检查本地事务状态
            boolean transactionExists = orderService.checkTransactionStatus(transactionId, messageBody);
            
            if (transactionExists) {
                System.out.println("本地事务状态确认成功，提交消息，TransactionId: " + transactionId);
                return LocalTransactionState.COMMIT_MESSAGE;
            } else {
                System.out.println("本地事务状态确认失败，回滚消息，TransactionId: " + transactionId);
                return LocalTransactionState.ROLLBACK_MESSAGE;
            }
        } catch (Exception e) {
            System.err.println("本地事务回查异常，TransactionId: " + transactionId + ", 错误: " + e.getMessage());
            return LocalTransactionState.UNKNOW;
        }
    }
}